import { h, render, ref, createVNode, nextTick } from 'vue';
import { ElDialog, ElButton } from 'element-plus';

export function showDialog(options = {}) {
    const {
        title = '提示',
        content = '',
        onConfirm = () => { },
        onCancel = () => {
            closeDialog()
        },
        showCancelButton = true, // 是否显示取消按钮
        confirmButtonText = '确定',
        cancelButtonText = '取消',
        width = '40vh',
    } = options;

    // 创建对话框容器
    const container = document.createElement('div');
    document.body.appendChild(container);

    // 对话框状态
    const dialogVisible = ref(true);

    // 关闭对话框
    const closeDialog = () => {
        dialogVisible.value = false;
        setTimeout(() => {
            render(null, container);
            document.body.removeChild(container);
        }, 300); // 等待动画完成
    };

    // 创建对话框 VNode
    const dialogVNode = createVNode(
        ElDialog,
        {
            title,
            visible: dialogVisible.value,
            'onUpdate:visible': (val) => (dialogVisible.value = val),
            width,
            'close-on-click-modal': false,
            'close-on-press-escape': false,
            'before-close': closeDialog,
        },
        {
            // 内容插槽
            content: () => typeof content === 'function'
                ? content()
                : h('div', { style: { padding: '20px 0' } }, content),

            // 底部按钮插槽
            footer: () => h('div', { class: 'dialog-footer' }, [
                showCancelButton && h(
                    ElButton,
                    { onClick: () => { onCancel(); closeDialog(); } },
                    () => cancelButtonText
                ),
                h(
                    ElButton,
                    {
                        type: 'primary',
                        onClick: () => { onConfirm(); closeDialog(); }
                    },
                    () => confirmButtonText
                )
            ])
        }
    );

    // 渲染对话框
    render(dialogVNode, container);

    // 返回关闭函数
    return closeDialog;
}